﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using CommunitySystem.Views;
using CommunitySystem.Ctrls;
using System.Collections.ObjectModel;
using CommunitySystem.PageView.晋升管理.新的晋升管理;
using CommunitySystem.JinShengService;
using EHR.Common;

namespace CommunitySystem.PageView
{
    public partial class PublicShowControl :  AsyncCtrl, IReturnListenerc
    {
        private JinShengService.JinShen_MainInfo _mainInfo = null;
        private ObservableCollection<JinShengService.JinShen_PublicShow_Detail> details = new ObservableCollection<JinShengService.JinShen_PublicShow_Detail>();

        private List<JinShengService.JinShen_DangGongWei_Detail> dgw = new List<JinShen_DangGongWei_Detail>();

        private JinShengService.JinShengServiceClient _client = null;
        private bool CanEditInfo = true;
        private bool CanSubmit = true;
        private bool CanConfirm = false;

        private string Role = "";
        public PublicShowControl(JinShengService.JinShen_MainInfo mainInfo)
        {
            InitializeComponent();
            IsWorking.Visibility = Visibility.Visible;
            _mainInfo = mainInfo;
         
            TextBlock tb = new TextBlock() { Text = "科室:" + mainInfo.Department, Margin = new Thickness(10, 0, 0, 0), VerticalAlignment = System.Windows.VerticalAlignment.Center };
            selectionInfo.Children.Add(tb);
            tb = new TextBlock() { Text = "职位:" + mainInfo.Position + "(" + mainInfo.PositionLevel + ")", Margin = new Thickness(60, 0, 0, 0), VerticalAlignment = System.Windows.VerticalAlignment.Center };
            selectionInfo.Children.Add(tb);

            _client = new JinShengService.JinShengServiceClient();
            #region
            _client.GetOrgForHRCompleted += (sender, e) =>
            {
                Role = e.Result;
                if (JinShenConst.Administrator.Contains(e.Result))
                {
                 
                    if (_mainInfo.Status == JinShenConst.STATUS_Candidate_Show)
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = false;
                    }
                    else
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = true;
                    }
                }
                else
                {
                    if (_mainInfo.Status == JinShenConst.STATUS_Party_Meeting || _mainInfo.Status == JinShenConst.STATUS_Candidate_Show)
                    {
                        btnSubmit.IsEnabled = true;
                        btnNext.IsEnabled = false;
                    }
                    else
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = true;
                    }
                }
               
                _client.GetJinShen_PublicShow_DetailAsync("MainID=" + _mainInfo.ID);
                
            };
            _client.GetOrgForHRAsync(EHR.Common.Session.LoginUser.LoginName);
            #endregion
            _client.GetJinShen_PublicShow_DetailCompleted += (sender, e) =>
            {
                details = e.Result;                
                _client.GetJinShen_DangGongWei_DetailCompleted += (sender1, e1) =>
                {
                    dgw = e1.Result.ToList();
                    if (details == null || details.Count <= 0)//新增
                    {
                        foreach (var d in e1.Result)
                        {
                            JinShengService.JinShen_PublicShow_Detail detail = new JinShengService.JinShen_PublicShow_Detail()
                            {
                                EmpID = d.EmpID,
                                EmpName = d.EmpName,
                                MainID = (int)d.MainID,
                            };
                            details.Add(detail);
                        }
                        
                    }
                    else//编辑
                    {
                       // btn.IsEnabled = CanSubmit;
                        foreach (var d in e1.Result)
                        {
                            var newDetails = details.Where(c => (int)c.EmpID == d.EmpID).FirstOrDefault();
                            if (newDetails == null)//有新增同意的情况
                            {
                                JinShengService.JinShen_PublicShow_Detail detail = new JinShengService.JinShen_PublicShow_Detail()
                                {
                                    EmpID = d.EmpID,
                                    EmpName = d.EmpName,
                                    MainID = (int)d.MainID,
                                };
                                details.Add(detail);
                                // btn.IsEnabled = false;

                            }
                            else
                            {
                                if (JinShenConst.Administrator.Contains(Role) && _mainInfo.Status == JinShenConst.STATUS_Candidate_Show)
                                btnNext.IsEnabled = false;
                                else btnNext.IsEnabled = true;
                            }
                        }
             
                    }
                    Init();
                };
                _client.GetJinShen_DangGongWei_DetailAsync("MainID=" + _mainInfo.ID + " and IsAgree = '同意'");
                //}
            };
           

            _client.SaveJinShenMainInfoCompleted += (sender, e) =>
            {
                if (e.Error == null && _mainInfo.Status == JinShenConst.STATUS_Candidate_Show)
                    _client.SaveJinShen_PublicShow_DetailAsync(details);

            };
            _client.UpdateJinShenMStatusCompleted += (sender, e) =>
            {


            };
            //消息
            _client.AddSystemInfoCompleted += (ss, ee) =>
            {

            };
            _client.SaveJinShen_PublicShow_DetailCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    _client.UpdateJinShenMStatusAsync(_mainInfo.MId, _mainInfo.Status);
                    SilverlightMessageBoxLibrary.Message.InfoMessage("公示结果上报成功!");
                    btnNext.IsEnabled = true;

                    //添加消息
                    SystemInfo sysinfo = new SystemInfo();
                    sysinfo.MenuId = 376;
                    sysinfo.MoKuai = "晋升管理";
                    sysinfo.MoKuaiSX = "确认任命";
                    sysinfo.DW1 = _mainInfo.OrgName;
                    sysinfo.CreateUser = Session.LoginUser.RealName;
                    sysinfo.CreateDate = DateTime.Now.ToString();
                    sysinfo.CreateUserID = 2;
                    sysinfo.OrgIDs = _mainInfo.OrgID.ToString();
                    sysinfo.LogUID = Session.LoginUser.UserID;
                    _client.AddSystemInfoAsync(sysinfo);
                }
            };
        }
        private ObservableCollection<JinShengService.JinShen_MainInfo> _mainInfos = null;
        private ObservableCollection<JinShen_MainInfo> SavemainInfos = null;
        public PublicShowControl(ObservableCollection<JinShengService.JinShen_MainInfo> mainInfos)
        {
            InitializeComponent();

            IsWorking.Visibility = Visibility.Visible;

            _mainInfos = mainInfos;
            //  btn.IsEnabled = false;
            btnNext.IsEnabled = false;

            gggg.Visibility = Visibility.Collapsed;
            _client = new JinShengService.JinShengServiceClient();
            #region
            _client.GetOrgForHRCompleted += (sender, e) =>
            {
                Role = e.Result;
                if (JinShenConst.Administrator.Contains(e.Result))
                {

                    if (mainInfos.First().Status == JinShenConst.STATUS_Candidate_Show)
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = false;
                    }
                    else
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = true;
                    }
                }
                else
                {
                    if (mainInfos.First().Status == JinShenConst.STATUS_Party_Meeting || mainInfos.First().Status == JinShenConst.STATUS_Candidate_Show)
                    {
                        btnSubmit.IsEnabled = true;
                        if( btnNext.IsEnabled == false)
                        btnNext.IsEnabled = false;
                    }
                    else
                    {
                        btnSubmit.IsEnabled = false;
                        btnNext.IsEnabled = true;
                    }
                }

            };
            _client.GetOrgForHRAsync(EHR.Common.Session.LoginUser.LoginName);
            #endregion
            #region
            JSControl4 js4 = null;
           
            foreach (var mainInfo in mainInfos)
            {
                _mainInfo = mainInfo;
                foreach (var d in mainInfo.DangGongWei_Detail.Where(p => p.MainID == mainInfo.ID).ToList().Where(p => p.IsAgree == "同意").ToList())
                {
                    dgw.Add(d);
                }
                if (mainInfo.PublicShow_Detail.Count != 0)
                {
                   
                    foreach (var item in mainInfo.PublicShow_Detail)
                    {
                        details.Add(item);
                    }
                    if (JinShenConst.Administrator.Contains(Role) && _mainInfo.Status == JinShenConst.STATUS_Candidate_Show)
                        btnNext.IsEnabled = false;
                    else btnNext.IsEnabled = true;
                }
                else
                {

                    foreach (var d in mainInfo.DangGongWei_Detail.Where(p => p.MainID == mainInfo.ID).ToList().Where(p => p.IsAgree == "同意").ToList())
                    {
                       
                        JinShengService.JinShen_PublicShow_Detail detail = new JinShengService.JinShen_PublicShow_Detail()
                        {
                            EmpID = d.EmpID,
                            EmpName = d.EmpName,
                            MainID = (int)d.MainID,
                        };
                        details.Add(detail);
                    }
                }

                js4 = new JSControl4(mainInfo, details,Role);
                spDetails1.Children.Add(js4);
            }
            IsWorking.Visibility = Visibility.Collapsed;
            #endregion

            //消息
            _client.AddSystemInfoCompleted += (ss, ee) =>
            {

            };
            _client.SaveJinShenMainInfosStatusCompleted += (sender, e) =>
            {

                if (e.Error == null)
                {
                   // _client.SaveJinShen_PublicShow_DetailAsync(details);
                    SavemainInfos = e.Result[0].JinShen_MainInfos;
                    SilverlightMessageBoxLibrary.Message.InfoMessage("公示结果上报成功!");
                    btnNext.IsEnabled = true;

                    //添加消息
                    SystemInfo sysinfo = new SystemInfo();
                    sysinfo.MenuId = 376;
                    sysinfo.MoKuai = "晋升管理";
                    sysinfo.MoKuaiSX = "确认任命";
                    sysinfo.DW1 = _mainInfo.OrgName;
                    sysinfo.CreateUser = Session.LoginUser.RealName;
                    sysinfo.CreateDate = DateTime.Now.ToString();
                    sysinfo.CreateUserID = 2;
                    sysinfo.OrgIDs = _mainInfo.OrgID.ToString();
                    sysinfo.LogUID = Session.LoginUser.UserID;
                    _client.AddSystemInfoAsync(sysinfo);
                }
            };

            _client.SaveJinShen_PublicShow_DetailCompleted += (sender, e) =>
            {
                if (e.Error == null)
                {
                    var Status = JinShenConst.STATUS_Candidate_Show;
                    _client.SaveJinShenMainInfosStatusAsync(_mainInfos, Status, _mainInfo.MId, EHR.Common.Session.LoginUser.LoginName);
               
                    //SilverlightMessageBoxLibrary.Message.InfoMessage("公示结果上报成功!");
                    //btnNext.IsEnabled = true;
                   
                }
            };

         
        }

        public void BeginReturn()
        {
            
        }

        private void Init()
        {
            foreach (var d in details)
            {
                Border b = new Border() { BorderBrush = new SolidColorBrush(Colors.Blue), BorderThickness = new Thickness(1), Margin = new Thickness(5) };
                StackPanel sp = new StackPanel() { Margin = new Thickness(3), DataContext = d };
                b.Child = sp;
                StackPanel sp1 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(3) };
                sp.Children.Add(sp1);

                TextBlock tb = new TextBlock() { Text = "经", Margin = new Thickness(0, 3, 0, 0) };
                sp1.Children.Add(tb);
                DatePicker dp = new DatePicker() { Margin = new Thickness(5, 0, 5, 0) };
                //if (CanEditInfo)
                    dp.IsEnabled = CanEditInfo;
                dp.SetBinding(DatePicker.SelectedDateProperty, new System.Windows.Data.Binding("StartDate") { Mode = System.Windows.Data.BindingMode.TwoWay, StringFormat = "yyyy-MM-dd" });
                sp1.Children.Add(dp);
                tb = new TextBlock() { Text = "至", Margin = new Thickness(0, 3, 0, 0) };
                sp1.Children.Add(tb);
                dp = new DatePicker() { Margin = new Thickness(5, 0, 5, 0) };
                //if (CanEditInfo)
                dp.IsEnabled = CanEditInfo;
                dp.SetBinding(DatePicker.SelectedDateProperty, new System.Windows.Data.Binding("EndDate") { Mode = System.Windows.Data.BindingMode.TwoWay, StringFormat = "yyyy-MM-dd" });
                sp1.Children.Add(dp);

                
                var dgwxx = dgw.Where(p => p.EmpID == d.EmpID).First();


               // tb = new TextBlock() { Text = "公示" + d.EmpName + "同志晋升" + _mainInfo.Position + "(" + _mainInfo.PositionLevel + ")", Margin = new Thickness(0, 3, 5, 0) };
                tb = new TextBlock() { Text = "公示" + d.EmpName + "同志晋升" + dgwxx.Position + "(" + dgwxx.AttributLevel + ")", Margin = new Thickness(0, 3, 5, 0) };
                sp1.Children.Add(tb);
                if (string.IsNullOrEmpty(d.Condition))
                {
                    d.Condition = "未收到情况反映";
                }
                DictComboBox dict = new DictComboBox() { Field = "Condition", DictCode = "HasProblem", DisplayMemberPath = "DictValue", SelectedValuePath = "DictValue", Width = 150 };
           
                sp1.Children.Add(dict);

                if (_mainInfo.PromotType.Equals("选举"))
                {
                    Button btxjjg = new Button() { Content = "选举结果", Margin = new Thickness(60, 0, 20, 0)};
                    btxjjg.Click += (sender11, e11) =>
                    {
                        _mainInfo.DangGongWei_Detail.Add(dgwxx);
                        XJJGWindow xjjg = new XJJGWindow(_mainInfo,d,Role);
                        xjjg.Show();
                        xjjg.Closed += (sender, e) => { };
                    };
                    sp1.Children.Add(btxjjg);
                }
               // if (CanEditInfo)
                dict.IsEnabled = CanEditInfo;
                StackPanel sp2 = new StackPanel() { Orientation = Orientation.Horizontal, Margin = new Thickness(3), DataContext = d };
                tb = new TextBlock() { Text = "反映情况:", Margin = new Thickness(0, 3, 0, 0) };
                sp2.Children.Add(tb);
               
                var box1 = new TextBox() { Width = 150, DataContext = d };
                box1.IsEnabled = CanEditInfo;
                box1.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("FanYinQingkuang") { Mode = System.Windows.Data.BindingMode.TwoWay });
                sp2.Children.Add(box1);

                dict.Tag = sp2;
                dict.SelectionChanged += (sender, e) =>
                {
                    var com = sender as DictComboBox;
                    var panel = com.Tag as StackPanel;
                    panel.Visibility = System.Windows.Visibility.Collapsed;
                    d.IsAgree = true;
                    var item =  dict.SelectedItem as DataService.DataDictionaryItemModel;
                    if (item.DictValue.Equals("有情况反映"))
                    {
                        panel.Visibility = System.Windows.Visibility.Visible;
                        d.IsAgree = false;
                    }
                    else
                    {
                        panel.Visibility = System.Windows.Visibility.Collapsed;
                        d.IsAgree = true;
                    }
                };
                tb = new TextBlock() { Text = "处理意见如下 : ", Margin = new Thickness(10,3,0,0) };
                sp2.Children.Add(tb);
                TextBox box = new TextBox() { Width = 150};
               // if (CanEditInfo)
                box.IsEnabled = CanEditInfo;
                box.SetBinding(TextBox.TextProperty, new System.Windows.Data.Binding("DSC") { Mode = System.Windows.Data.BindingMode.TwoWay });

                
                tb = new TextBlock() { Text = "是否同意晋升 : ", Margin = new Thickness(10, 3, 0, 0) };
                var dict1 = new ComboBox() { DisplayMemberPath = "DictValue", SelectedValuePath = "DictCode", Width = 150, DataContext = d };
                dict1.ItemsSource = CommunitySystem.Common.InitialDictionary._Dicts["IsAgreePromot"].Item;
                if (d.IsAgree == true)
                {
                    dict1.SelectedIndex = 0;
                    d.IsAgree = true;
                }
                else
                {
                    dict1.SelectedIndex = 1;
                    d.IsAgree = false;
                }
                dict1.SelectionChanged += (sender, e) =>
                {
                    if (dict1.SelectedIndex == 0)
                    {
                        d.IsAgree = true;
                    }
                    else
                    {
                        d.IsAgree = false;
                    }
                };
                dict1.IsEnabled = CanEditInfo;
                sp2.Children.Add(box);

                sp2.Children.Add(tb);
                sp2.Children.Add(dict1);
                
                sp.Children.Add(sp2);

                
                
               


                spDetails.Children.Add(b);
            }

            IsWorking.Visibility = Visibility.Collapsed;
        }


        /// <summary>
        /// 公示结果上报
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ImageButton_Click(object sender, RoutedEventArgs e)
        {
            if (Validate())
            {
                if (_mainInfos == null)
                {
                    _mainInfo.Status = JinShenConst.STATUS_Candidate_Show;
                    _client.SaveJinShenMainInfoAsync(_mainInfo);
                }
                else
                {
                    _client.SaveJinShen_PublicShow_DetailAsync(details);
                   }
            }
        }


        bool Validate()
        {
            if (details != null && details.Count > 0)
            {
                var d = details.Where(c => c.Condition == "有情况反映").FirstOrDefault();
                if (d != null)
                {
                    if (string.IsNullOrEmpty(d.FanYinQingkuang))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(d.EmpName+"反映情况不能为空!");
                        return false;
                    }

                    if (string.IsNullOrEmpty(d.DSC))
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(d.EmpName + "处理意见不能为空!");
                        return false;
                    }
                }
                foreach (var item in details)
                {
                    if (item.StartDate == null||item.EndDate==null)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName + "公示时间不能为空!");
                        return false;
                    }
                    if (item.StartDate > item.EndDate)
                    {
                        SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName+"结束时间不能早于开始时间!");
                        return false;
                    }
                    foreach (var item1 in dgw.Where(p=>p.EmpID==item.EmpID).ToList())
                    {
                        if (item1.MeetingDate > item.StartDate)
                        {
                            SilverlightMessageBoxLibrary.Message.ErrorMessage(item.EmpName+"公示的开始时间不能早于党（工）委（组）考察时间!");
                            return false;
                        }
                    }
                }
            }
            else
            {
                return false;
            }
            return true;
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (_mainInfos == null)
            {
                NextPublicShowControl control = new NextPublicShowControl(_mainInfo) { Nav = this.Nav };
                Nav.ShowNextPage("确定任命", control as AsyncCtrl);
            }
            if (_mainInfos != null)
            {

                //if (SavemainInfos == null) SavemainInfos = _mainInfos;
                //NextPublicShowControl control = new NextPublicShowControl(SavemainInfos) { Nav = this.Nav };
                //Nav.ShowNextPage("确定任命", control as AsyncCtrl);


                _client.GetJinShen_MainInfosCompleted -= new EventHandler<JinShengService.GetJinShen_MainInfosCompletedEventArgs>(_client_GetJinShen_MainInfosCompleted);
                _client.GetJinShen_MainInfosCompleted += new EventHandler<JinShengService.GetJinShen_MainInfosCompletedEventArgs>(_client_GetJinShen_MainInfosCompleted);
                _client.GetJinShen_MainInfosAsync(string.Format("1=1 and jsm.ID={0}", _mainInfos.First().MId), Session.LoginUser.LoginName);
           
            }
        }
        void _client_GetJinShen_MainInfosCompleted(object sender, JinShengService.GetJinShen_MainInfosCompletedEventArgs e)
        {
            NextPublicShowControl control = new NextPublicShowControl(e.Result[0].JinShen_MainInfos) { Nav = this.Nav };
            Nav.ShowNextPage("确定任命", control as AsyncCtrl);
        }
        
    }
}
